import Vue from 'vue';

import $ from 'jquery';
import 'froala-editor';
import 'froala-editor/js/languages/zh_cn';
import 'froala-editor/js/plugins/align.min';
import 'froala-editor/js/plugins/colors.min';
import 'froala-editor/js/plugins/font_family.min';
import 'froala-editor/js/plugins/font_size.min';
import 'froala-editor/css/plugins/colors.min.css'

import {SEALS} from '../../config/static';

import domtoimage from 'dom-to-image';
import FileSaver from 'file-saver';

console.log(SEALS);

const DEFAULT_SEAL_WIDTH = 200;

export default {
	data () {
		return {
			imageDataUrl: '',
			editorInst: null,
			awardTemplate: {
				backgroundUrl: '',
				sprites: [/*{
				 type: 'text',
				 content: '测试文字',
				 x: 500,
				 y: 500
				 }, {
				 type: 'picture',
				 imageSrc: 'https://sundries.oss-cn-beijing.aliyuncs.com/lw/admin_dashboard/seal.png',
				 width: 200,
				 height: 200,
				 x: 500,
				 y: 500
				 }*/]
			},
			seals: SEALS,

			render: {
				bgOriginWidth: 0,
				bgOriginHeight: 0,
				bgScale: 1,

				previewContainerWidth: 0,
				previewContainerHeight: 0
			},

			backgroundImages: [
				'https://sundries.oss-cn-beijing.aliyuncs.com/lw/admin_dashboard/background/2017%E7%BD%91%E8%81%9A%E5%B0%91%E5%B9%B4%E5%A5%96%E7%8A%B6-%E2%80%9C%E4%B8%AD%E5%9B%BD%E5%86%9B%E9%AD%82%E2%80%9D%E5%86%9B%E4%BA%8B%E7%9F%A5%E8%AF%86%E7%AB%9E%E8%B5%9B.jpg',
				'https://sundries.oss-cn-beijing.aliyuncs.com/lw/admin_dashboard/background/800-1.png',
				'https://sundries.oss-cn-beijing.aliyuncs.com/lw/admin_dashboard/background/moban.png',
				'https://sundries.oss-cn-beijing.aliyuncs.com/lw/admin_dashboard/background/%E5%B0%91%E5%85%88%E9%98%9F%E7%9F%A5%E8%AF%86%E5%A4%A7%E6%AF%94%E6%8B%BC%E7%9F%A5%E8%AF%86%E7%AB%9E%E8%B5%9B-1.png'
			],

			variables: [{
				name: 'name',
				placeholder: '姓名'
			}, {
				name: 'active',
				placeholder: '活动项目'
			}, {
				name: 'award',
				placeholder: '奖项名称'
			}],

			activeSpriteIndex: -1,

			drag: {
				draggingIndex: -1,
				mouseDownX: 0,
				mouseDownY: 0,

				mouseDownSpriteX: 0,
				mouseDownSpriteY: 0,

				mouseDownSpriteWidth: 0,
				mouseDownSpriteHeight: 0,

				resizer: '', // nw | ne | sw | se
				spriteRatio: 0
			},

			bgPickerVisible: false,
			bgUrlTemp: '',
			$previewContainer: null,
			$bgEl: null
		};
	},
	mounted() {
		$('#editor').froalaEditor({
			language: 'zh_cn',
			toolbarButtons: ['color', 'fontFamily', 'fontSize'],
			fontFamily: {
				'SimSun': '宋体',
				'SimHei': '黑体',
				'Microsoft YaHei': '微软雅黑',
				'PingFang SC': '苹方',
				'Apple LiGothic Medium': 'test'
			}
		});

		$('#editor').on('froalaEditor.contentChanged', (e, editor, keyupEvent) => {
			if (this.activeSpriteIndex > -1) {
				this.awardTemplate.sprites[this.activeSpriteIndex].content = editor.html.get(true);
			}
		});

		this.$previewContainer = this.$el.querySelector('.award-preview');
		this.$bgEl = this.$el.querySelector('.bg-image');

		this.$bgEl.addEventListener('load', () => {
			this.$nextTick(() => {
				console.log('BG LOADED');

				this.fitBg();
			});
		});

		this.applyContainerSize();

		window.addEventListener('resize', this.fitBg);
	},
	methods: {
		activateSprite(i) {
			this.activeSpriteIndex = i;

			let currSprite = this.awardTemplate.sprites[i];
			if (currSprite.type === 'text' || currSprite.type === 'variable') {
				$('#editor').froalaEditor('html.set', currSprite.content);
				if (currSprite.type === 'variable') {
					$('#editor').froalaEditor('edit.off');
				} else {
					$('#editor').froalaEditor('edit.on');
				}
			}
		},
		addText() {
			this.awardTemplate.sprites.push({
				type: 'text',
				content: '<span style="font-size: 30px;">请输入内容</span>',
				x: 0,
				y: 0
			});
			this.activateSprite(this.awardTemplate.sprites.length - 1);
		},
		addVariable(i) {
			if (!this.variableExist(i)) {
				let variable = this.variables[i];
				this.awardTemplate.sprites.push({
					type: 'variable',
					name: variable.name,
					content: `<span style="font-size: 12px;">${variable.placeholder}</span>`,
					x: 0,
					y: 0
				});
				this.activateSprite(this.awardTemplate.sprites.length - 1);
			}
		},
		addSeal(i) {
			let sealUrl = this.seals[i].seal_url;
			this.getImageRect(sealUrl).then(({width, height}) => {
				this.awardTemplate.sprites.push({
					type: 'picture',
					imageSrc: sealUrl,
					width: DEFAULT_SEAL_WIDTH,
					height: DEFAULT_SEAL_WIDTH / (width / height),
					// name: this.seals[i].organization,
					x: 0,
					y: 0
				});
				this.activateSprite(this.awardTemplate.sprites.length - 1);
			});
		},
		fileChanged(e, type) {
			if (e.currentTarget.files && e.currentTarget.files[0]) {
				let reader = new FileReader();
				reader.addEventListener('load', (e) => {
					if (type === 'background') {
						this.imageDataUrl = e.target.result;
					} else if (type === 'picture') {
						this.getImageRect(e.target.result).then(({width, height}) => {
							this.awardTemplate.sprites.push({
								type: 'picture',
								imageSrc: e.target.result,
								width: DEFAULT_SEAL_WIDTH,
								height: DEFAULT_SEAL_WIDTH / (width / height),
								x: 0,
								y: 0
							});
						});
					}
				}, {once: true});
				reader.readAsDataURL(e.currentTarget.files[0]);
			}
		},
		getImageRect(url){
			return new Promise((resolve, reject) => {
				let img = new Image();
				img.addEventListener('load', function () {
					resolve(img);
				});
				img.src = url;
			});
		},
		exportImage() {
			this.activeSpriteIndex = -1;
			this.$nextTick(() => {
				domtoimage.toJpeg(this.$el.querySelector('.image-edit'), {
					quality: 1
				}).then(function (dataUrl) {
					var link = document.createElement('a');
					link.download = 'my-image-name.jpeg';
					link.href = dataUrl;
					link.click();
				});
			});
		},
		getSpriteStyle(sprite) {
			let style = {
				transform: `translateX(${sprite.x * this.render.bgScale}px) translateY(${sprite.y * this.render.bgScale}px)`
			};
			if (sprite.type === 'picture') {
				style.width = `${sprite.width * this.render.bgScale}px`;
				style.height = `${sprite.height * this.render.bgScale}px`
			}
			return style;
		},
		removeSprite() {
			this.awardTemplate.sprites.splice(this.activeSpriteIndex, 1);
			this.activateSprite(this.awardTemplate.sprites.length - 1);
		},
		pickBackgroundImage() {
			this.bgPickerVisible = true;
		},
		selectBg(bgUrl) {
			this.awardTemplate.backgroundUrl = bgUrl;

			this.render.bgOriginWidth = 0;
			this.render.bgOriginHeight = 0;

			this.bgPickerVisible = false;
		},
		/*confirmSelect() {
		 this.awardTemplate.backgroundUrl = this.bgUrlTemp;
		 },*/

		spriteMouseDown(e, i) {

			this.drag.draggingIndex = i;
			this.drag.mouseDownX = e.clientX;
			this.drag.mouseDownY = e.clientY;

			let currSprite = this.awardTemplate.sprites[this.drag.draggingIndex];

			let targetEl = e.path[0],
				targetElClassList = targetEl.className.split(/\s+/);
			if (targetElClassList.indexOf('resizer') > -1) {
				// 调整大小
				this.drag.resizer = ['nw', 'ne', 'sw', 'se'].find(item => {
					return targetElClassList.indexOf(item) > -1;
				});

				this.drag.mouseDownSpriteWidth = currSprite.width;
				this.drag.mouseDownSpriteHeight = currSprite.height;

				this.spriteRatio = currSprite.width / currSprite.height;
			} else {
				// 拖拽位置
				this.drag.resizer = '';
			}

			this.drag.mouseDownSpriteX = currSprite.x;
			this.drag.mouseDownSpriteY = currSprite.y;

			document.addEventListener('mousemove', this.spriteMouseMove);
			document.addEventListener('mouseup', this.spriteMouseUp);
		},
		spriteMouseMove(e) {
			let currSprite = this.awardTemplate.sprites[this.drag.draggingIndex],
				offsetX = e.clientX - this.drag.mouseDownX,
				offsetY = e.clientY - this.drag.mouseDownY;
			if (this.drag.resizer === '') {
				currSprite.x = this.drag.mouseDownSpriteX + offsetX / this.render.bgScale;
				currSprite.y = this.drag.mouseDownSpriteY + offsetY / this.render.bgScale;
			} else {
				let deltaX = 0, deltaY = 0;
				if (Math.abs(offsetX) > Math.abs(offsetY)) {
					deltaX = offsetX / this.render.bgScale;
					deltaY = (offsetX / this.spriteRatio) / this.render.bgScale;

					if (['ne', 'sw'].indexOf(this.drag.resizer) > -1) {
						deltaY = -deltaY;
					}
				} else {
					deltaY = offsetY / this.render.bgScale;
					deltaX = (offsetY * this.spriteRatio) / this.render.bgScale;

					if (['ne', 'sw'].indexOf(this.drag.resizer) > -1) {
						deltaX = -deltaX;
					}
				}
				switch (this.drag.resizer) {
					case 'nw':
						currSprite.x = this.drag.mouseDownSpriteX + deltaX;
						currSprite.y = this.drag.mouseDownSpriteY + deltaY;
						currSprite.width = this.drag.mouseDownSpriteWidth - deltaX;
						currSprite.height = this.drag.mouseDownSpriteHeight - deltaY;
						break;
					case 'ne':
						// currSprite.x = this.drag.mouseDownSpriteX + deltaX;
						currSprite.y = this.drag.mouseDownSpriteY + deltaY;
						currSprite.width = this.drag.mouseDownSpriteWidth + deltaX;
						currSprite.height = this.drag.mouseDownSpriteHeight - deltaY;
						break;
					case 'sw':
						currSprite.x = this.drag.mouseDownSpriteX + deltaX;
						// currSprite.y = this.drag.mouseDownSpriteY + deltaY;
						currSprite.width = this.drag.mouseDownSpriteWidth - deltaX;
						currSprite.height = this.drag.mouseDownSpriteHeight + deltaY;
						break;
					case 'se':
						// currSprite.x = this.drag.mouseDownSpriteX + deltaX;
						// currSprite.y = this.drag.mouseDownSpriteY + deltaY;
						currSprite.width = this.drag.mouseDownSpriteWidth + deltaX;
						currSprite.height = this.drag.mouseDownSpriteHeight + deltaY;
						break;
				}
			}
		},
		spriteMouseUp(e) {
			document.removeEventListener('mousemove', this.spriteMouseMove);
			document.removeEventListener('mouseup', this.spriteMouseUp);
		},

		applyContainerSize() {
			let rect = this.$previewContainer.getBoundingClientRect();
			this.render.previewContainerWidth = rect.width - 20;
			this.render.previewContainerHeight = rect.height - 20;
		},

		fitBg() {
			this.applyContainerSize();
			if (this.render.bgOriginWidth === 0) {
				let newImg = new Image();
				newImg.onload = () => {
					this.render.bgOriginWidth = newImg.width;
					this.render.bgOriginHeight = newImg.height;

					fit.call(this);
				};
				newImg.src = this.awardTemplate.backgroundUrl;
			} else {
				fit.call(this);
			}

			function fit () {
				console.log(this.render.previewContainerWidth);
				if (this.render.previewContainerWidth / this.render.previewContainerHeight > this.render.bgOriginWidth / this.render.bgOriginHeight) {
					// portrait
					this.render.bgScale = this.render.previewContainerHeight / this.render.bgOriginHeight;
				} else {
					// landscape
					this.render.bgScale = this.render.previewContainerWidth / this.render.bgOriginWidth;
				}

			}
		},

		variableExist(i) {
			let addedVars = this.awardTemplate.sprites.filter((item) => item.type === 'variable');
			if (addedVars.length > 0) {
				return addedVars.findIndex(item => item.name && item.name === this.variables[i].name) > -1;
			} else {
				return false;
			}
		},

		showJson(){
			console.log(JSON.stringify(this.awardTemplate));
		}
	},
	computed: {
		getTextStyle() {
			return {transform: `scale(${this.render.bgScale})`};
		},
		previewContainerStyle() {
			return {
				width: `${this.render.bgOriginWidth * this.render.bgScale}px`,
				height: `${this.render.bgOriginHeight * this.render.bgScale}px`
			};
		}
	},
	beforeDestroy() {
		window.removeEventListener('resize', this.fitBg);
	}
};